package de.le.mfw.client.main.view.widget;

import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.HasClickHandlers;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.PasswordItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.layout.VLayout;

import de.le.mfw.client.main.view.validator.MinLengthValidator;

public class LoginWidget {

	private boolean isActive;
	private final Window window;
	private DynamicForm form = new DynamicForm();
	private IButton loginButton = new IButton("Anmelden");

	public LoginWidget() {
		window = createWindow();
	}

	private Window createWindow() {
		Window window = new Window();
		window.setAutoSize(true);
		window.setShowMinimizeButton(false);
		window.setAutoCenter(true);
		window.setIsModal(true);
		window.setShowModalMask(true);
		window.setTitle("Login");

		VLayout vLayout = new VLayout();
		vLayout.setWidth(250);
		vLayout.setMembersMargin(5);
		vLayout.setLayoutMargin(10);

		form = createForm();
		vLayout.addMember(form);

		loginButton.setWidth100();
		vLayout.addMember(loginButton);

		window.addItem(vLayout);
		return window;
	}

	private DynamicForm createForm() {
		TextItem usernameField = new TextItem();
		usernameField.setName("nick");
		usernameField.setTitle("Nick");
		usernameField.setRequired(true);
		usernameField.setValidators(new MinLengthValidator(4));

		PasswordItem passwordField = new PasswordItem();
		passwordField.setName("password");
		passwordField.setTitle("Passwort");
		passwordField.setRequired(true);
		passwordField.setValidators(new MinLengthValidator(8));

		form.setFields(usernameField, passwordField);
		form.setRequiredMessage("wird benötigt");
		form.setWidth100();
		form.draw();
		return form;
	}

	public void show() {
		window.show();
		isActive = true;
	}

	public void hide() {
		window.hide();
		isActive = false;
	}

	public boolean isActive() {
		return isActive;
	}

	public boolean isValid() {
		return form.validate();
	}

	public HasClickHandlers getLoginButton() {
		return loginButton;
	}

	public String getNick() {
		return (String) form.getValue("nick");
	}

	public String getPassword() {
		return (String) form.getValue("password");
	}
}
